package pri.hillchen.std.netty.timeserver.bio;

import java.io.*;
import java.net.Socket;
import java.util.Date;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 11:32 2018/3/30 0030.
 */
public class TimeServerHandler implements Runnable {
    public static final String QUERY_TIME_COMMAND = "CURRENT_TIME";
    private Socket socket;

    public TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;

        try{
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);

            String currentTime = null;
            String body = null;

            while (true){
                body = in.readLine();
                if(body == null){
                    break;
                }
                System.out.println(String.format("The time server receive order : " + body));
                currentTime = QUERY_TIME_COMMAND.equals(body) ? new Date(System.currentTimeMillis()).toString() : " BAD ORDER";
                out.println(currentTime);
            }

        }catch (Exception e){

        }finally {
            if(in != null){
                try {
                    in.close();
                    in = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null){
                out.close();
                out = null;
            }
            if(this.socket != null){
                try {
                    this.socket.close();
                    this.socket = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            System.out.println("handel req end !");
        }
    }
}
